<template>
  <div class="customer-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      :disabled="mode === 'view'"
    >
      <!-- 基本信息 -->
      <el-card class="form-section" header="基本信息">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户编码" prop="customerCode">
              <el-input v-model="formData.customerCode" placeholder="系统自动生成" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="formData.customerName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户类型" prop="customerType">
              <el-select v-model="formData.customerType" placeholder="请选择客户类型" style="width: 100%">
                <el-option label="一级批发商" value="level1" />
                <el-option label="二级批发商" value="level2" />
                <el-option label="零售商" value="retailer" />
                <el-option label="连锁超市" value="chain" />
                <el-option label="电商平台" value="ecommerce" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="正常" value="active" />
                <el-option label="暂停" value="suspended" />
                <el-option label="黑名单" value="blacklist" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 联系信息 -->
      <el-card class="form-section" header="联系信息">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="formData.contactPerson" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="传真号码" prop="fax">
              <el-input v-model="formData.fax" placeholder="请输入传真号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="联系地址" prop="address">
              <el-input
                v-model="formData.address"
                type="textarea"
                :rows="2"
                placeholder="请输入详细联系地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 资质信息 -->
      <el-card class="form-section" header="资质信息">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="营业执照号" prop="businessLicense">
              <el-input v-model="formData.businessLicense" placeholder="请输入营业执照号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税务登记号" prop="taxNumber">
              <el-input v-model="formData.taxNumber" placeholder="请输入税务登记号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="法人代表" prop="legalRepresentative">
              <el-input v-model="formData.legalRepresentative" placeholder="请输入法人代表" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册资本" prop="registeredCapital">
              <el-input-number
                v-model="formData.registeredCapital"
                :min="0"
                :precision="2"
                placeholder="请输入注册资本"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成立日期" prop="establishDate">
              <el-date-picker
                v-model="formData.establishDate"
                type="date"
                placeholder="选择成立日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经营范围" prop="businessScope">
              <el-input v-model="formData.businessScope" placeholder="请输入经营范围" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 信用信息 -->
      <el-card class="form-section" header="信用信息">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="信用等级" prop="creditLevel">
              <el-select v-model="formData.creditLevel" placeholder="请选择信用等级" style="width: 100%">
                <el-option label="AAA级" value="AAA" />
                <el-option label="AA级" value="AA" />
                <el-option label="A级" value="A" />
                <el-option label="B级" value="B" />
                <el-option label="C级" value="C" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信用额度" prop="creditLimit">
              <el-input-number
                v-model="formData.creditLimit"
                :min="0"
                :precision="2"
                placeholder="请输入信用额度"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="已用额度" prop="usedCredit">
              <el-input-number
                v-model="formData.usedCredit"
                :min="0"
                :precision="2"
                placeholder="已用信用额度"
                style="width: 100%"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可用额度">
              <el-input
                :value="availableCredit"
                placeholder="可用信用额度"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账期天数" prop="paymentTerms">
              <el-input-number
                v-model="formData.paymentTerms"
                :min="0"
                :max="365"
                placeholder="请输入账期天数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算方式" prop="settlementMethod">
              <el-select v-model="formData.settlementMethod" placeholder="请选择结算方式" style="width: 100%">
                <el-option label="现金" value="cash" />
                <el-option label="银行转账" value="transfer" />
                <el-option label="支票" value="check" />
                <el-option label="信用证" value="credit" />
                <el-option label="月结" value="monthly" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 价格信息 -->
      <el-card class="form-section" header="价格信息">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格等级" prop="priceLevel">
              <el-select v-model="formData.priceLevel" placeholder="请选择价格等级" style="width: 100%">
                <el-option label="VIP" value="VIP" />
                <el-option label="一级" value="一级" />
                <el-option label="二级" value="二级" />
                <el-option label="三级" value="三级" />
                <el-option label="普通" value="普通" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="折扣率(%)" prop="discountRate">
              <el-input-number
                v-model="formData.discountRate"
                :min="0"
                :max="100"
                :precision="2"
                placeholder="请输入折扣率"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最小订货量" prop="minOrderQuantity">
              <el-input-number
                v-model="formData.minOrderQuantity"
                :min="0"
                placeholder="请输入最小订货量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送费用" prop="deliveryFee">
              <el-input-number
                v-model="formData.deliveryFee"
                :min="0"
                :precision="2"
                placeholder="请输入配送费用"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 银行信息 -->
      <el-card class="form-section" header="银行信息">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户银行" prop="bankName">
              <el-input v-model="formData.bankName" placeholder="请输入开户银行" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input v-model="formData.bankAccount" placeholder="请输入银行账号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户名" prop="accountName">
              <el-input v-model="formData.accountName" placeholder="请输入开户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行地址" prop="bankAddress">
              <el-input v-model="formData.bankAddress" placeholder="请输入银行地址" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 其他信息 -->
      <el-card class="form-section" header="其他信息">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions" v-if="mode !== 'view'">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        {{ mode === 'add' ? '创建客户' : '更新客户' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  customerData: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'add', // add, edit, view
    validator: (value) => ['add', 'edit', 'view'].includes(value)
  }
})

// Emits
const emit = defineEmits(['save', 'cancel'])

// 响应式数据
const formRef = ref()
const saving = ref(false)

// 表单数据
const formData = reactive({
  id: null,
  customerCode: '',
  customerName: '',
  customerType: '',
  status: 'active',
  contactPerson: '',
  contactPhone: '',
  email: '',
  fax: '',
  address: '',
  businessLicense: '',
  taxNumber: '',
  legalRepresentative: '',
  registeredCapital: 0,
  establishDate: '',
  businessScope: '',
  creditLevel: '',
  creditLimit: 0,
  usedCredit: 0,
  paymentTerms: 30,
  settlementMethod: '',
  priceLevel: '',
  discountRate: 0,
  minOrderQuantity: 0,
  deliveryFee: 0,
  bankName: '',
  bankAccount: '',
  accountName: '',
  bankAddress: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  customerType: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入联系地址', trigger: 'blur' }],
  businessLicense: [{ required: true, message: '请输入营业执照号', trigger: 'blur' }],
  taxNumber: [{ required: true, message: '请输入税务登记号', trigger: 'blur' }],
  creditLevel: [{ required: true, message: '请选择信用等级', trigger: 'change' }],
  creditLimit: [{ required: true, message: '请输入信用额度', trigger: 'blur' }],
  priceLevel: [{ required: true, message: '请选择价格等级', trigger: 'change' }]
}

// 计算属性
const availableCredit = computed(() => {
  const available = (formData.creditLimit || 0) - (formData.usedCredit || 0)
  return `¥${available.toLocaleString()}`
})

// 方法
const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    saving.value = true
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    emit('save', { ...formData })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saving.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

const initFormData = () => {
  if (props.customerData) {
    Object.assign(formData, props.customerData)
  } else {
    // 新增模式，设置默认值
    formData.status = 'active'
    formData.paymentTerms = 30
    formData.usedCredit = 0
  }
}

// 监听器
watch(() => props.customerData, () => {
  initFormData()
}, { immediate: true })

watch(() => props.mode, (newMode) => {
  if (newMode === 'add') {
    saving.value = false
  }
})

// 生命周期
onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.customer-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 20px;
}

.form-actions {
  margin-top: 20px;
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.form-actions .el-button {
  margin-left: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .customer-form {
    max-height: 60vh;
  }
  
  .form-actions {
    text-align: center;
  }
  
  .form-actions .el-button {
    margin: 0 6px;
  }
}
</style>